package com.xzc.shopping.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.shopping.common.BaseResponse;
import com.xzc.shopping.common.ErrorCode;
import com.xzc.shopping.common.ResultUtils;
import com.xzc.shopping.mapper.UserMapper;
import com.xzc.shopping.model.domain.User;
import com.xzc.shopping.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.xzc.shopping.constant.UserConstant.USER_LOGIN_STATE;


@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {

    @Resource
    private UserMapper userMapper;
    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "xzc";

    @Override
    public BaseResponse<User> userLogin(String userName, String password, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userName, password)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        if (userName.length() < 4) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        if (password.length() < 6) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userName);
        if (matcher.find()) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }

        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName", userName);
        queryWrapper.eq("password", password);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.error("user login failed, userName cannot match password");
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);

        }
        //  记录用户的登录态
        HttpSession session = request.getSession();
        session.setAttribute(USER_LOGIN_STATE, user);
        log.info("Session ID: {} | User stored: {}", session.getId(), user);
        return ResultUtils.success(user);
    }
}
